package club.babyf.nativeai.controller;

import club.babyf.nativeai.service.IWechatCallbackService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * WechatCallbackController.
 *
 * @author zhanglei.
 * @date 2023/4/9 13:17.
 * @description 微信回调控制器.
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/wechat")
public class WechatCallbackController {

    private final WxMpService wxMpService;

    private final IWechatCallbackService wechatCallbackService;

    /**
     * 签名验证
     *
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机数字符串
     * @return 验证结果
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(
            @RequestParam(name = "signature", required = false) String signature,
            @RequestParam(name = "timestamp", required = false) String timestamp,
            @RequestParam(name = "nonce", required = false) String nonce,
            @RequestParam(name = "echostr", required = false) String echostr) {
        // 验签
        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        } else {
            return "非法请求";
        }
    }

    /**
     * 消息接收
     *
     * @param signature   签名
     * @param timestamp   时间戳
     * @param nonce       随机数
     * @param requestBody 请求体
     * @return 消息回复
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestBody String requestBody) {
        // 验签
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            return "非法请求";
        }
        // 消息处理
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
        // 返回结果
        return Objects.requireNonNull(wechatCallbackService.syncHandleMessage(inMessage)).toXml();
    }

}
